package com.jsyso.jsyso.web;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jsyso.jsyso.util.BeanUtils;
import com.jsyso.jsyso.util.JsMap;

/**
 * HTTPServlet基类
 * @author janjan, xujian_jason@163.com
 *
 */
public abstract class JHttpServlet extends javax.servlet.http.HttpServlet {
	private static final long serialVersionUID = 1L;

	protected Logger logger = LoggerFactory.getLogger(getClass());
	private JsMap initParams;
	
	@SuppressWarnings("unchecked")
	@Override
	public void init() throws ServletException {
		initParams = JsMap.create();
		ServletConfig config = getServletConfig();
		Enumeration<String> en = config.getInitParameterNames();
		while (en.hasMoreElements()) {
			String property = en.nextElement();
			String value = StringUtils.deleteWhitespace(config.getInitParameter(property));
			initParams.set(property, value);
			if(isSetter())
				BeanUtils.invokeSetter(this, property, value);
		}
		initServlet(config);
	}
	
	protected void initServlet(ServletConfig config) {}
	
	/**
	 * 是否设置属性
	 */
	protected boolean isSetter() {
		return true;
	}
	
	/**
	 * 获取初始化参数
	 */
	protected JsMap getInitParams() {
		return initParams;
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	protected final void processRequest(HttpServletRequest request, HttpServletResponse response) {
		Throwable failureCause = null;
		try {
			doService(request, response);
		} catch (Exception e) {
			failureCause = e;
			throw new RuntimeException(e);
		} finally {
			if(failureCause != null) {
				logger.error("Request processing failed", failureCause);
			}
		}
	}
	
	protected abstract void doService(HttpServletRequest request, HttpServletResponse response);
	
}
